<script>
import { bindFile, fetchProductFile } from "@/api/product";
import { fileTypes } from "@/utils/constant/pms";
import Upload from "@/components/Upload/index.vue";

export default {
  name: "productBindFile",
  components: { Upload },
  data() {
    return {
      productId: undefined,
      fileTypeOptions: [],
      fileTypes: {
        10: {
          accept: "image/*",
          listType: "picture-card",
        },
        11: {
          accept: ".pdf",
          listType: "text",
        },
        12: {
          accept: ".pdf",
          listType: "text",
        },
      },
    };
  },
  created() {
    this.productId = this.$route.query.id;
    const rawOptions = fileTypes.toKeyValueArray();
    this.fileTypeOptions = rawOptions.map((item) => ({
      ...item,
      files: [],
    }));
    this.getProductFileList();
  },
  methods: {
    getProductFileList() {
      fetchProductFile(this.productId).then((response) => {
        this.formatFileList(response.data);
      });
    },
    formatFileList(files) {
      this.fileTypeOptions = this.fileTypeOptions.map((typeItem) => {
        if (!typeItem.files) {
          typeItem.files = [];
        }
        files.forEach((file) => {
          if (file.fileType === typeItem.value) {
            typeItem.files.push({
              name: file.fileName,
              url: file.fileUrl,
            });
          }
        });
        return typeItem;
      });
    },
    handleUpload() {
      const data = this.fileTypeOptions.map((item) => {
        return item.files.map((file) => ({
          fileName: file.name,
          fileType: item.value,
          fileUrl: file.url,
          productId: this.productId,
        }));
      });
      bindFile([].concat(...data)).then(() => {
        this.$message({
          type: "success",
          message: "上传成功",
          duration: 1000,
        });
        this.$router.back();
      });
    },
  },
};
</script>

<template>
  <div class="app-container">
    <el-card
      shadow="never"
      :class="index > 0 ? 'table-container' : ''"
      v-for="(item, index) in fileTypeOptions"
      :header="item.label"
      :key="item.value"
    >
      <upload
        v-model="item.files"
        :max-count="Infinity"
        :multiple="true"
        :accept="fileTypes[item.value].accept"
        :list-type="fileTypes[item.value].listType"
        value-type="obj-array"
      >
        <el-button size="small" type="primary">选择</el-button>
      </upload>
    </el-card>

    <el-row class="table-container" justify="center" type="flex">
      <el-button type="primary" @click="handleUpload">保存</el-button>
    </el-row>
  </div>
</template>

<style scoped></style>
